package com.jackchan.homework.sysw.service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jackchan.homework.sysw.dto.MaterialDto;
import com.jackchan.homework.sysw.dto.NutritionCommonDto;
import com.jackchan.homework.sysw.entity.Material;
import com.jackchan.homework.sysw.entity.Nutritive;
import com.jackchan.homework.sysw.entity.Stock;
import com.jackchan.homework.sysw.repository.MaterialDao;
import com.jackchan.homework.sysw.repository.NutritiveDao;
import com.jackchan.homework.sysw.repository.StockDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by ch-hui on 15/12/20.
 */
@Service
public class MaterialService {

    @Autowired
    private MaterialDao materialDao;

    @Autowired
    private NutritiveDao nutritiveDao;

    @Autowired
    private StockDao stockDao;

    private static final Integer NORMAL = 1;

    public Iterable<Material> findAll() {
        return materialDao.findAll();
    }


    public List<MaterialDto> findAllDto() {
        List<MaterialDto> dtoes = Lists.newArrayList();

        for (Iterator<Material> materials = materialDao.findByOpType(NORMAL).iterator(); materials.hasNext(); ) {
            Material material = materials.next();
            Stock stock = stockDao.findByMaterial(material);
            MaterialDto dto = new MaterialDto();
            if (stock != null) {
                dto.setStockQuantity(stock.getQuantity());
            } else {
                dto.setStockQuantity(0d);
            }

            if (material != null) {
                dto.setId(material.getId());
                dto.setEnterPrice(material.getLastEnterPrice());
                dto.setMarkPrice(material.getCurrentMarketPrice());
                dto.setName(material.getName());
                dto.setCfn(material.getCfn());
            }
            dtoes.add(dto);
        }
        return dtoes;
    }

    public Material findOne(Long id) {
        return materialDao.findOne(id);
    }

    public Nutritive findByMaterial(Material material) {
        return nutritiveDao.findByMaterial(material);
    }


    public NutritionCommonDto findNutriCommonByMaterial(Material material){
        Nutritive nutrition = this.findByMaterial(material);
        return this.getNutritionCommon(nutrition);
    }



    public NutritionCommonDto getNutritionCommon(Nutritive nu){
        NutritionCommonDto dto = new NutritionCommonDto();
        dto.setAdf(nu.getAdf());
        dto.setAsh(nu.getAsh());
        return dto;
    }
}
